<template>
  <view class="login-container">
    <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
    <button type="warn" class="btn-style" @click="getUserInfo">一键登录</button>
    <view class="tips-text">登录后享用更多权益</view>
  </view>
</template>

<script>
  import {myLogin} from '../service/login_api.js'
  import {mapMutations,mapState} from 'vuex'
  export default {
    name:"my-login",
    data() {
      return {
        
      };
    },
    computed:{
      ...mapState('m_user',['redirectInfo'])
    },
    methods:{
      ...mapMutations('m_user',['updateUserInfo','updateToken','updateRedirectInfo']),
      
      //获取用户基本信息并保存到本地
    async getUserInfo(){
        const res = await this.handleUserInfo().catch(err => err)
        this.updateUserInfo(res.userInfo)
        
        this.getToken(res)
      },
      
    //获取token
    async getToken(info){
      //获取code
      const [err, res] = await uni.login().catch(err => err)
      if(err || res.errMsg !== 'login:ok') return uni.$showMessage('登录失败！')
      const code = res.code
      //整合登录所需参数
      const query = {
        code,
        encryptedData: info.encryptedData,
        iv: info.iv,
        rawData :info.rawData,
        signature: info.signature
      }
      //登录接口感觉有问题，写死token假装获取
      let token = await myLogin(query)
      token ="abc"
      if(token){
        uni.$showMessage('登录成功！')
        this.updateToken(token)
        this.navigateBack()
      }
    },
      //封装uni.getUserProfile
     handleUserInfo(){
        return new Promise((resolve,reject) => {
         uni.getUserProfile({
           desc:"登录",
           success(res){
             resolve(res)
           },
           fail(err) {
             uni.$showMessage('您拒绝了登录！')
             reject(err)
           }
         })
        })
      },
      
      //登录成功后跳回页面
      navigateBack(){
        if(this.redirectInfo && this.redirectInfo.openType === 'switchTab'){
          uni.switchTab({
            url:this.redirectInfo.from,
            complete: () => {
              this.updateRedirectInfo(null)
            }
          })
        }
      }
    }
  }
</script>

<style lang="scss">
  
.login-container{
  display: flex;
  margin-top:200rpx;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  
  .btn-style{
    width:600rpx;
    border-radius: 50px;
  }
  .tips-text{
    margin-top:10px;
    font-size:13px;
    color:gray;
  }
}
</style>
